package com.ask.forMe.service.impl;

import com.ask.forMe.mapper.GroupBuyTeamMapper;
import com.ask.forMe.model.entity.GroupBuyMember;
import com.ask.forMe.model.entity.GroupBuyTeam;
import com.ask.forMe.model.entity.Order;
import com.ask.forMe.service.GroupBuyMemberService;
import com.ask.forMe.service.GroupBuyTeamService;
import com.ask.forMe.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GroupBuyTeamServiceImpl extends ServiceImpl<GroupBuyTeamMapper, GroupBuyTeam> implements GroupBuyTeamService {
    @Autowired
    private GroupBuyTeamMapper groupBuyTeamMapper;
    @Autowired
    private GroupBuyMemberService groupBuyMemberService;
    @Autowired
    private OrderService orderService;


    /**
     * 完成拼单
     *
     * @param teamId
     */
    @Override
    public void completeTeam(Long teamId) {
        GroupBuyTeam team = getById(teamId);
        team.setStatus(GroupBuyTeam.STATUS_COMPLETED);
        save(team);


        // todo 通知商家进行发货
    }

    /**
     * 处理超时拼团
     */
    @Override
    @Transactional
    public void processTimeoutTeams() {
        // 查询过期的拼团
        QueryWrapper<GroupBuyTeam> wrapper = new QueryWrapper<>();
        wrapper.lt("expire_time", LocalDateTime.now()).eq("status", GroupBuyTeam.STATUS_ACTIVE);
        List<GroupBuyTeam> teams = groupBuyTeamMapper.selectList(wrapper);


        // 跟新拼团状态
        List<Long> teamIds = new ArrayList<>();
        List<GroupBuyTeam> teamsToUpdate = new ArrayList<>();

        for (GroupBuyTeam team : teams) {
            team.setStatus(GroupBuyTeam.STATUS_FAILED);  // 使用合适的失败状态
            teamsToUpdate.add(team);
            teamIds.add(team.getId());
        }
        // 批量更新拼团状态
        if (!teamsToUpdate.isEmpty()) {
            updateBatchById(teamsToUpdate);
        }

        // 批量查询所有相关成员
        QueryWrapper<GroupBuyMember> memberWrapper = new QueryWrapper<>();
        memberWrapper.in("team_id", teamIds);
        List<GroupBuyMember> allMembers = groupBuyMemberService.list(memberWrapper);

        // 5. 收集订单ID
        List<Long> orderIds = allMembers.stream()
                .map(GroupBuyMember::getOrderId)
                .collect(Collectors.toList());

        orderIds.forEach(id -> {
            Order order = orderService.getById(id);
            order.setStatus(Order.STATUS_CANCEL);
            orderService.updateById(order);
        });

        // todo: 执行退款操作、恢复商品库存、发送用户通知
    }
}
